package com.biwin.module.security.starter.handler;

import cn.hutool.json.JSONUtil;
import com.biwin.common.app.enums.BwSecurityExceptionEnum;
import com.biwin.common.app.vo.BwResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Access Definition handler
 *
 * @author biwin
 * @since 0.0.1
 */
@Component
public class BwAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException e) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        BwResponse bwResponse = BwResponse.response(BwSecurityExceptionEnum.NO_PERMISSIONS);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSONUtil.toJsonStr(bwResponse));
    }
}
